package ds_industry_2025.industry.gy_04.T3

import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions._
/*
    3、编写Scala代码，使用Spark根据dwd_ds_hudi层的fact_change_record表关联dim_machine表统计每个车间中所有设备运行时长
    （即设备状态为“运行”）的中位数在哪个设备（为偶数时，两条数据原样保留输出），若某个设备运行状态当前未结束（即change_end_time值
    为空）则该状态不参与计算，计算结果存入ClickHouse数据库shtd_industry的machine_running_median表中（表结构如下），然后
    在Linux的ClickHouse命令行中根据所属车间、设备id均为降序排序，查询出前5条数据，将SQL语句复制粘贴至客户端桌面【Release\任
    务B提交结果.docx】中对应的任务序号下，将执行结果截图粘贴至客户端桌面【Release\任务B提交结果.docx】中对应的任务序号下;
 */
object t3 {
  def main(args: Array[String]): Unit = {
    val spark = SparkSession.builder()
      .master("local[*]")
      .appName("t3")
      .config("hive.exec.dynamic.partition.mode","nonstrict")
      .config("spark.serializer","org.apache.spark.serializer.KryoSerializer")
      .config("spark.sql.extensions","org.apache.spark.sql.hudi.HoodieSparkSessionExtension")
      .enableHiveSupport()
      .getOrCreate()

    val fact_change_record_path="hdfs://192.168.40.110:9000/user/hive/warehouse/hudi_gy_dwd.db/fact_change_record"
    val dim_machine_path="hdfs://192.168.40.110:9000/user/hive/warehouse/hudi_gy_dwd.db/dim_machine"

    spark.read.format("hudi").load(fact_change_record_path)
      .where(col("changerecordstate")===lit("运行"))
      .createOrReplaceTempView("t1")

    spark.read.format("hudi").load(dim_machine_path)
      .createOrReplaceTempView("t2")

    //  todo 拿到每条数据的运行时间
    val r1 = spark.sql(
      """
        |select
        |t1.changemachineid as machine_id,
        |t2.machinefactory as factory,
        |(unix_timestamp(t1.changeendtime) - unix_timestamp(t1.changestarttime))  as run_time
        |from t1
        |join t2 on t2.basemachineid=t1.changemachineid
        |""".stripMargin)

    //  todo 求每个厂房的中位数
    val r2 = r1.groupBy("factory")
      .agg(
        expr("percentile_approx(run_time,0.5)").as("median_time")
      )


    //  todo 得到结果
    val result = r1.join(r2, "factory")
      .filter(col("run_time") === col("median_time"))
      .withColumnRenamed("factory", "machine_factory")
      .withColumnRenamed("run_time", "total_amount_time")
      .select("machine_id", "machine_factory", "total_amount_time")
      .distinct()

//
//    result.write.format("jdbc")
//      .option("url","jdbc:clickhouse://192.168.40.110:8123/shtd_industry")
//      .option("user","default")
//      .option("password","")
//      .option("driver","com.clickhouse.jdbc.ClickHouseDriver")
//      .option("dbtable","machine_running_median")
//      .mode("append")
//      .save()

    result.show





    spark.close()
  }

}
